package core.storage;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Class modeling the XML Serialization
 * 
 * @author Nolan Potier
 * @version 1.0.0
 * 
 */
public abstract class XMLSerializer {

    /**
     * Load an object with a file name
     * @param fileName
     * @return Object
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static Object load(String fileName) throws FileNotFoundException,
            IOException {
        Object object = null;

        String nomFichier = fileName + ".xml";

        XMLDecoder decoder = new XMLDecoder(new FileInputStream(nomFichier));
        try {
            object = decoder.readObject();
        } finally {
            decoder.close();
        }
        return object;
    }

    /**
     * Store an object in XML
     * @param object
     * @param fileName
     * @return boolean
     * @throws FileNotFoundException
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static boolean store(Object object, String fileName)
            throws FileNotFoundException, IOException {

        if (object == null)
            return false;

        String nomFichier = fileName + ".xml";

        XMLEncoder encoder = new XMLEncoder(new FileOutputStream(nomFichier));
        try {
            encoder.writeObject(object);
            encoder.flush();
        } finally {
            encoder.close();
            return true;
        }
    }

}
